<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>基于主题文字的文章生成</title>
    <script src="https://cdn.socket.io/4.0.0/socket.io.min.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            background-color: #f8f9fa;
            min-height: 100vh;
        }

        .container {
            max-width: 100%;
            margin: 0;
            background: white;
            border-radius: 0;
            box-shadow: none;
            overflow: hidden;
        }

        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 15px 30px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            box-shadow: none;
        }

        .header-content {
            flex: 1;
            min-width: 0;
        }

        .nav-links {
            padding: 0 0 0 20px;
            background: transparent;
            display: flex;
            gap: 10px;
        }

        .nav-links a {
            white-space: nowrap;
        }

        .nav-links a {
            display: inline-block;
            margin-right: 15px;
            padding: 8px 15px;
            background: #9370DB; /* 柔和的纯紫色背景 */
            color: white;
            text-decoration: none;
            border-radius: 20px; /* 增加圆角 */
            font-size: 14px;
            transition: all 0.3s ease;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); /* 减弱阴影 */
        }

        .nav-links a:hover {
            transform: translateY(-1px);
            box-shadow: 0 3px 6px rgba(0, 0, 0, 0.15);
        }

        .main-content {
            padding: 40px;
            border-bottom: 2px solid #ccc;
        }

        .form-group {
            margin-bottom: 25px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            color: #555;
            font-size: 16px;
        }

        .form-control {
            width: 100%;
            padding: 12px 15px;
            border: 2px solid #e1e5e9;
            border-radius: 8px;
            font-size: 16px;
            transition: border-color 0.3s ease;
        }

        .form-control:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        .textarea-large {
            min-height: 200px;
            resize: vertical;
            font-family: inherit;
            line-height: 1.6;
        }

        .char-count {
            text-align: right;
            font-size: 12px;
            color: #6c757d;
            margin-top: 5px;
        }

        .btn {
            padding: 15px 30px;
            border: none;
            border-radius: 8px;
            font-size: 16px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-block;
            text-align: center;
        }

        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(102, 126, 234, 0.3);
        }

        .btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none !important;
        }

        .controls-row {
            display: flex;
            gap: 20px;
            align-items: end;
        }

        .controls-row .form-group {
            flex: 1;
        }

        .controls-row .btn {
            flex-shrink: 0;
            margin-bottom: 0;
        }

        .alert {
            padding: 15px 20px;
            border-radius: 8px;
            margin: 20px 0;
            font-size: 14px;
        }

        .alert-success {
            background-color: #d4edda;
            border: 1px solid #c3e6cb;
            color: #155724;
        }

        .alert-error {
            background-color: #f8d7da;
            border: 1px solid #f5c6cb;
            color: #721c24;
        }

        .alert-info {
            background-color: #d1ecf1;
            border: 1px solid #bee5eb;
            color: #0c5460;
        }

        .loading {
            display: none;
            text-align: center;
            padding: 30px;
        }

        .loading.show {
            display: block;
        }

        .spinner {
            border: 3px solid #f3f3f3;
            border-top: 3px solid #667eea;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
            margin: 0 auto 15px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .tips {
            background: #f8f9fa;
            border: 1px solid #e1e5e9;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 30px;
        }

        .tips h3 {
            color: #667eea;
            margin-bottom: 10px;
            font-size: 1.1em;
        }

        .tips ul {
            padding-left: 20px;
        }

        .tips li {
            margin-bottom: 5px;
            color: #666;
        }

        @media (max-width: 768px) {
            .controls-row {
                flex-direction: column;
                gap: 15px;
            }

            .controls-row .btn {
                width: 100%;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <div class="header-content">
                <h1>基于主题文字的文章生成</h1>
                <p>输入多个文字内容，智能生成高质量文章</p>
            </div>
            <div class="nav-links">
                <a href="/">🏠 首页</a>
                <a href="/hot-topic">🔥 热点采集与分析</a>
                <a href="/editor">📝 文章编辑与查看</a>
            </div>
        </div>


        <div class="main-content">
            <div class="tips">
                <h3>💡 使用提示</h3>
                <ul>
                    <li>在下方输入框中输入多个关键词、短语或段落，用换行分隔</li>
                    <li>AI会根据您输入的内容智能生成一篇连贯的文章</li>
                    <li>建议输入3-10个相关的主题词汇或简短描述</li>
                    <li>输入内容越丰富，生成的文章质量越高</li>
                    <li>生成的文章将自动保存为Markdown格式</li>
                </ul>
            </div>

            <div class="section-title">📝 输入内容</div>

            <div class="form-group">
                <label for="content-input">请输入多个文字内容（每行一个主题或关键词）：</label>
                <textarea 
                    id="content-input" 
                    class="form-control textarea-large" 
                    placeholder="请输入您想要生成文章的关键词或主题内容，例如：&#10;人工智能发展趋势&#10;机器学习在生活中的应用&#10;未来科技对社会的影响&#10;数字化转型的挑战与机遇&#10;&#10;每行输入一个主题或关键词，AI将根据这些内容生成一篇完整的文章。"
                    oninput="updateCharCount()"
                ></textarea>
                <div class="char-count" id="char-count">0 字符</div>
            </div>

            <div class="controls-row">
                <div class="form-group">
                    <label for="ai-model-select">选择AI模型：</label>
                    <select id="ai-model-select" class="form-control">
                        <option value="qwen">Qwen (通义千问)</option>
                        <option value="kimi">Kimi-K2</option>
                        <option value="spark">Spark</option>
                    </select>
                </div>

                <button id="generate-btn" class="btn btn-primary" onclick="generateArticle()">
                    🚀 生成文章
                </button>
            </div>

            <div id="result-container">
                <!-- 结果将在这里显示 -->
            </div>
        </div>
    </div>

    <script>
        let socket = null;
        let currentTaskId = null;

        // 初始化WebSocket连接
        function initSocket() {
            socket = io();
            
            socket.on('connect', () => {
                console.log('WebSocket连接成功');
            });
            
            socket.on('disconnect', () => {
                console.log('WebSocket连接断开');
            });
            
            socket.on('task_update', (data) => {
                handleTaskUpdate(data);
            });
        }

        // 处理任务更新
        function handleTaskUpdate(data) {
            if (data.task_id !== currentTaskId) {
                return;
            }
            
            const container = document.getElementById('result-container');
            
            if (data.status === 'generating_title') {
                container.innerHTML = `
                    <div class="loading show">
                        <div class="spinner"></div>
                        <p>正在分析输入内容并生成标题...</p>
                    </div>
                `;
            } else if (data.status === 'generating_article') {
                container.innerHTML = `
                    <div class="loading show">
                        <div class="spinner"></div>
                        <p>正在生成文章内容...</p>
                        <p>使用标题: ${data.title || '生成中...'}</p>
                    </div>
                `;
            } else if (data.status === 'saving') {
                container.innerHTML = `
                    <div class="loading show">
                        <div class="spinner"></div>
                        <p>正在保存文章...</p>
                    </div>
                `;
            } else if (data.status === 'completed') {
                container.innerHTML = `
                    <div class="alert alert-success">
                        <h4>✅ 文章生成成功！</h4>
                        <p><strong>生成标题:</strong> ${data.final_title}</p>
                        <p><strong>文件名:</strong> ${data.filename}</p>
                        <p><strong>文件路径:</strong> ${data.file_path}</p>
                        <p>文章已保存到本地文件！正在跳转到编辑页面...</p>
                        <p>如果页面跳转失败，请自行访问 <a href="/editor" target="_blank">编辑页面</a></p>
                    </div>
                `;
                
                // 重置按钮状态
                const btn = document.getElementById('generate-btn');
                btn.disabled = false;
                btn.textContent = '🚀 生成文章';
                currentTaskId = null;
                
                // 2秒后跳转到编辑页面
                setTimeout(() => {
                    window.open('/editor', '_blank');
                }, 2000);
            } else if (data.status === 'error') {
                container.innerHTML = `
                    <div class="alert alert-error">
                        <p>❌ ${data.error}</p>
                    </div>
                `;
                
                // 重置按钮状态
                const btn = document.getElementById('generate-btn');
                btn.disabled = false;
                btn.textContent = '生成文章';
                currentTaskId = null;
            }
        }

        // 更新字符计数
        function updateCharCount() {
            const input = document.getElementById('content-input');
            const counter = document.getElementById('char-count');
            const length = input.value.length;
            counter.textContent = `${length} 字符`;
            
            if (length > 2000) {
                counter.style.color = '#dc3545';
            } else if (length > 1000) {
                counter.style.color = '#ffc107';
            } else {
                counter.style.color = '#6c757d';
            }
        }

        // 生成文章
        async function generateArticle() {
            const content = document.getElementById('content-input').value.trim();
            const aiModel = document.getElementById('ai-model-select').value;
            
            if (!content) {
                showAlert('error', '请输入要生成文章的内容');
                return;
            }

            if (content.length < 10) {
                showAlert('error', '输入内容太短，请至少输入10个字符');
                return;
            }

            const btn = document.getElementById('generate-btn');
            const container = document.getElementById('result-container');
            
            btn.disabled = true;
            btn.textContent = '生成中...';
            
            container.innerHTML = `
                <div class="loading show">
                    <div class="spinner"></div>
                    <p>正在初始化生成任务...</p>
                    <p>使用AI模型: ${aiModel.toUpperCase()}</p>
                </div>
            `;

            try {
                const response = await fetch('/api/generate-article-from-content', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ 
                        content: content,
                        ai_model: aiModel 
                    })
                });

                const result = await response.json();

                if (result.success) {
                    currentTaskId = result.data.task_id;
                    showAlert('info', '任务已启动，请等待生成完成...');
                } else {
                    showAlert('error', result.error);
                    btn.disabled = false;
                    btn.textContent = '🚀 生成文章';
                }
            } catch (error) {
                console.error('请求失败:', error);
                showAlert('error', '请求失败，请稍后重试');
                btn.disabled = false;
                btn.textContent = '🚀 生成文章';
            }
        }

        // 显示提示信息
        function showAlert(type, message) {
            const container = document.getElementById('result-container');
            const alertDiv = document.createElement('div');
            alertDiv.className = `alert alert-${type}`;
            alertDiv.innerHTML = `<p>${message}</p>`;
            container.appendChild(alertDiv);

            // 5秒后自动移除提示信息（除了错误信息）
            if (type !== 'error') {
                setTimeout(() => {
                    if (alertDiv.parentNode) {
                        alertDiv.parentNode.removeChild(alertDiv);
                    }
                }, 5000);
            }
        }

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            initSocket();
            updateCharCount();
            
            // 添加回车键快捷生成
            document.getElementById('content-input').addEventListener('keydown', function(event) {
                if (event.ctrlKey && event.key === 'Enter') {
                    generateArticle();
                }
            });
        });
    </script>
<script>
    function clearHotTopicsCacheAndNavigate() {
        sessionStorage.removeItem('cachedHotTopics');
        window.location.href = '/';
    }
</script>
</body>
</html>